<template>
    <div class="card-header">30天用电趋势</div>
    <div style="flex: 1" v-loading="loading">
        <BaseChart :responsive="true" v-if="!loading" :options="chartOption" />
    </div>
</template>

<script setup>
import { getMetersReportApi } from "@/api/meter";
import { useCompanyStore } from "@/stores/company";
import { useMeterStore } from "@/stores/meter";
import dayjs from "dayjs";
import { watch, ref } from "vue";
import { handleError } from "@/utils/handleError";
import { getMeterInfoApi } from "@/api/meter";
import convertToTreeData from "@/utils/convertToTreeData";
let meterStore = useMeterStore();
let loading = ref(false);
let companyStore = useCompanyStore();
let firstLevelData = ref([]);
let chartOption = ref({
    xAxisData: [],
    yAxisUnit: "kWh",
    series: [
        {
            name: "一级表",
            data: [],
            type: "line",
        }
    ],
    hideXAxis: true,
    hideYAxis: true,
    customColors: ["#8D8D8D"],
});
const emit = defineEmits(["hasData"]);

const meterLevels = ref([]);

const time = {
    start_time: dayjs().subtract(30, 'day').startOf('day').valueOf(),
    end_time: dayjs().startOf('day').valueOf(),
    interval: "day",
}

// 使用统一时间配置
async function getFirstLevelData() {

    // 检查一级表数据是否存在
    if (!meterLevels.value || meterLevels.value.length === 0) {
        return;
    }

    try {
        const res = await getMetersReportApi({
            meters: meterLevels.value,
            ...time,
        });

        // 检查返回数据
        if (!res || !res.aggregated_data) {

            firstLevelData.value = [];
            return;
        }

        firstLevelData.value = res.aggregated_data || [];
    } catch (error) {
        handleError(error, '获取一级表数据失败');
        firstLevelData.value = [];
    }
}

function generateFullMonthData() {
    // 生成最近30天的日期数组（不包含今天）
    const dates = [];
    const labels = [];

    for (let i = 30; i > 0; i--) {
        const date = dayjs().subtract(i, 'day');
        dates.push(date.format('YYYY-MM-DD'));
        labels.push(date.format('MM-DD'));
    }

    return { fullMonthDates: dates, fullMonthLabels: labels };
}

function setChartOption() {
    // 生成完整月份的日期数据
    const { fullMonthDates, fullMonthLabels } = generateFullMonthData();

    // 将一级表数据整理成映射表，方便后续查找
    const firstLevelMap = {};
    if (Array.isArray(firstLevelData.value)) {
        firstLevelData.value.forEach(item => {
            if (item && item.start_time) {
                const dateKey = dayjs(item.start_time).format('YYYY-MM-DD');
                firstLevelMap[dateKey] = Number(item.Value);
            }
        });
    }

    // 根据完整月份生成数据系列
    const firstLevelValues = fullMonthDates.map(date => {
        const value = firstLevelMap[date];
        return value !== undefined && !isNaN(value) ? +value.toFixed(2) : 0;
    });

    // 设置图表选项
    chartOption.value = {
        xAxisData: fullMonthLabels,
        yAxisUnit: "kWh",
        series: [
            {
                name: "一级表",
                data: firstLevelValues,
                type: "line",
            }
        ],
        hideXAxis: true,
        hideYAxis: true,
    };
}

async function fetchData() {
    try {
        loading.value = true;

        // 检查公司信息
        if (!companyStore?.currentCompany?.id) {

            loading.value = false;
            return;
        }

        const res = await getMeterInfoApi({
            company_id: companyStore.currentCompany.id,
            type: 2,
        });

        if (!res || !res.data || res.data.length === 0) {
            emit("hasData", false)
            return;
        }

        emit("hasData", true)

        meterLevels.value = await convertToTreeData(res.data);
        await getFirstLevelData();
        setChartOption();
    } catch (error) {
        handleError(error, '获取用电趋势数据失败');
        // 设置空的图表数据
        const { fullMonthLabels } = generateFullMonthData();
        chartOption.value = {
            xAxisData: fullMonthLabels,
            yAxisUnit: "kWh",
            series: [
                { name: "一级表", data: Array(fullMonthLabels.length).fill(0), type: "line" },
            ],
            customColors: ["#8D8D8D"],
        };
    } finally {
        loading.value = false;
    }
}

watch(
    () => companyStore.currentCompany,
    async () => {
        fetchData();
    },
    {
        immediate: true,
    }
);
</script>

<style scoped></style>